<template>
  <div class="complaint-list-container">
    <!-- 搜索区域 -->
    <el-card class="search-card">
      <el-form :model="searchForm" inline>
        <el-form-item label="售后ID">
          <el-input v-model="searchForm.afterSalesId" placeholder="请输入售后服务ID" clearable style="width: 180px" />
        </el-form-item>
        <el-form-item label="满意度评分">
          <el-select
            v-model="searchForm.satisfactionLevel"
            placeholder="请选择满意度评分"
            clearable
            style="width: 180px"
          >
            <el-option v-for="i in 5" :key="i" :label="`${i}分`" :value="i" />
          </el-select>
        </el-form-item>
        <el-form-item label="回复时间">
          <el-date-picker
            v-model="searchForm.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD"
            clearable
            style="width: 330px"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 表格工具栏 -->
    <div class="table-toolbar">
      <el-button type="success" @click="handleExport">导出</el-button>
    </div>

    <!-- 表格区域 -->
    <el-card class="table-card">
      <el-table
        v-loading="loading"
        :data="tableData"
        border
        row-key="id"
        stripe
        highlight-current-row
        style="width: 100%"
      >
        <el-table-column prop="id" label="ID" width="80" align="center" />
        <el-table-column prop="afterSalesId" label="售后服务ID" width="100" align="center" />
        <el-table-column prop="complaintContent" label="投诉内容" min-width="200" show-overflow-tooltip />
        <el-table-column prop="replyContent" label="回复内容" min-width="200" show-overflow-tooltip />
        <el-table-column prop="replyTime" label="回复时间" width="150" align="center" />
        <el-table-column prop="satisfactionLevel" label="满意度评分" width="200" align="center">
          <template #default="scope">
            <el-rate
              v-if="scope.row.satisfactionLevel"
              v-model="scope.row.satisfactionLevel"
              disabled
              show-score
              text-color="#ff9900"
              score-template="{value}"
            />
            <span v-else>暂无评分</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="150" align="center">
          <template #default="scope">
            <el-button type="primary" link @click="handleView(scope.row)">查看</el-button>
            <el-button type="success" link @click="handleReply(scope.row)" v-if="!scope.row.replyContent"
              >回复</el-button
            >
            <el-button
              type="warning"
              link
              @click="handleRate(scope.row)"
              v-if="scope.row.replyContent && !scope.row.satisfactionLevel"
              >评价</el-button
            >
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pagination.total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          background
        />
      </div>
    </el-card>

    <!-- 查看详情对话框 -->
    <el-dialog v-model="viewDialogVisible" title="投诉详情" width="650px" destroy-on-close>
      <el-descriptions :column="1" border>
        <el-descriptions-item label="ID">{{ currentComplaint.id }}</el-descriptions-item>
        <el-descriptions-item label="售后服务ID">{{ currentComplaint.afterSalesId }}</el-descriptions-item>
        <el-descriptions-item label="投诉内容">{{ currentComplaint.complaintContent }}</el-descriptions-item>
        <el-descriptions-item label="回复内容">{{ currentComplaint.replyContent || "暂无回复" }}</el-descriptions-item>
        <el-descriptions-item label="回复时间">{{ currentComplaint.replyTime || "暂无" }}</el-descriptions-item>
        <el-descriptions-item label="满意度评分">
          <el-rate
            v-if="currentComplaint.satisfactionLevel"
            v-model="currentComplaint.satisfactionLevel"
            disabled
            show-score
            text-color="#ff9900"
            score-template="{value}"
          />
          <span v-else>暂无评分</span>
        </el-descriptions-item>
        <el-descriptions-item label="创建时间">{{ currentComplaint.createTime }}</el-descriptions-item>
      </el-descriptions>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="viewDialogVisible = false">关闭</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 回复对话框 -->
    <el-dialog v-model="replyDialogVisible" title="回复投诉" width="650px" destroy-on-close>
      <el-form ref="replyFormRef" :model="replyForm" :rules="replyFormRules" label-width="100px" status-icon>
        <el-form-item label="投诉内容">
          <el-input v-model="replyForm.complaintContent" type="textarea" :rows="3" disabled />
        </el-form-item>
        <el-form-item label="回复内容" prop="replyContent">
          <el-input v-model="replyForm.replyContent" type="textarea" :rows="3" placeholder="请输入回复内容" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="replyDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitReply">提交回复</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 评价对话框 -->
    <el-dialog
      v-model="rateDialogVisible"
      title="提交满意度评价"
      width="580px"
      destroy-on-close
      custom-class="rating-dialog"
    >
      <div class="rating-container">
        <div class="complaint-box">
          <div class="box-header">
            <i class="el-icon-chat-dot-round"></i>
            <span>投诉内容</span>
          </div>
          <div class="content-box">{{ rateForm.complaintContent }}</div>
        </div>

        <div class="reply-box">
          <div class="box-header">
            <i class="el-icon-s-comment"></i>
            <span>回复内容</span>
          </div>
          <div class="content-box">{{ rateForm.replyContent }}</div>
        </div>

        <div class="rate-box">
          <div class="rate-title">
            <i class="el-icon-star-on"></i>
            <span>您的评价</span>
          </div>
          <div class="rate-content">
            <el-rate
              v-model="rateForm.satisfactionLevel"
              show-score
              score-template="{value}分"
              :colors="['#F7BA2A', '#F7BA2A', '#F7BA2A']"
              :max="5"
              :texts="['很差', '较差', '一般', '较好', '很好']"
              show-text
            />
            <div class="rate-tips">{{ getRatingTips() }}</div>
          </div>
        </div>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="rateDialogVisible = false" plain>取消</el-button>
          <el-button type="primary" @click="submitRating" :disabled="rateForm.satisfactionLevel <= 0"
            >提交评价</el-button
          >
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from "vue";
import { ElMessage } from "element-plus";
import { getComplaintReplyList, updateComplaintReply, submitSatisfactionRating } from "@/api/complaint";
import { formatToLocalDateTime } from "@/utils/date";
import { getComplaintReplyListExcel } from "@/api/export";

// 搜索表单
const searchForm = reactive({
  afterSalesId: "",
  satisfactionLevel: "",
  dateRange: [],
});

// 表格数据
const loading = ref(false);
const tableData = ref([]);

// 分页
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0,
});

// 查看详情相关
const viewDialogVisible = ref(false);
const currentComplaint = ref({});

// 回复相关
const replyDialogVisible = ref(false);
const replyFormRef = ref(null);
const replyForm = reactive({
  id: null,
  afterSalesId: null,
  complaintContent: "",
  replyContent: "",
});
const replyFormRules = {
  replyContent: [{ required: true, message: "请输入回复内容", trigger: "blur" }],
};

// 评价相关
const rateDialogVisible = ref(false);
const rateFormRef = ref(null);
const rateForm = reactive({
  id: null,
  complaintContent: "",
  replyContent: "",
  satisfactionLevel: 0,
});

// 初始化
onMounted(() => {
  fetchComplaintList();
});

// 获取投诉回复列表
const fetchComplaintList = async () => {
  loading.value = true;

  try {
    const params = {
      afterSalesId: searchForm.afterSalesId || undefined,
      satisfactionLevel: searchForm.satisfactionLevel || undefined,
      replyTimeStart: searchForm.dateRange?.[0] || undefined,
      replyTimeEnd: searchForm.dateRange?.[1] || undefined,
      current: pagination.currentPage,
      size: pagination.pageSize,
    };

    const response = await getComplaintReplyList(params);

    if (response.success) {
      pagination.total = response.data.total;
      tableData.value = response.data.list;
    } else {
      tableData.value = [];
      pagination.total = 0;
    }
  } catch (error) {
    console.error("获取投诉回复列表失败:", error);
    tableData.value = [];
    pagination.total = 0;
  } finally {
    loading.value = false;
  }
};

// 处理搜索
const handleSearch = () => {
  pagination.currentPage = 1;
  fetchComplaintList();
};

// 重置搜索
const resetSearch = () => {
  Object.keys(searchForm).forEach((key) => {
    if (key === "dateRange") {
      searchForm[key] = [];
    } else {
      searchForm[key] = "";
    }
  });
  handleSearch();
};

// 处理分页大小变化
const handleSizeChange = (size) => {
  pagination.pageSize = size;
  fetchComplaintList();
};

// 处理当前页变化
const handleCurrentChange = (page) => {
  pagination.currentPage = page;
  fetchComplaintList();
};

// 处理查看详情
const handleView = (row) => {
  currentComplaint.value = { ...row };
  viewDialogVisible.value = true;
};

// 处理回复
const handleReply = (row) => {
  replyForm.id = row.id;
  replyForm.afterSalesId = row.afterSalesId;
  replyForm.complaintContent = row.complaintContent;
  console.log(row);
  replyForm.replyContent = "";
  replyDialogVisible.value = true;
};

// 提交回复
const submitReply = async () => {
  if (!replyFormRef.value) return;

  try {
    const valid = await replyFormRef.value.validate();
    if (!valid) return;

    const data = {
      id: replyForm.id,
      afterSalesId: replyForm.afterSalesId,
      complaintContent: replyForm.complaintContent,
      replyContent: replyForm.replyContent,
      replyTime: formatToLocalDateTime(new Date()),
    };

    const response = await updateComplaintReply(data);

    if (response.success) {
      ElMessage.success("回复成功");
      replyDialogVisible.value = false;
      fetchComplaintList(); // 刷新列表
    } else {
      ElMessage.error(response.message || "回复失败");
    }
  } catch (error) {
    console.error("提交回复失败:", error);
    ElMessage.error("提交回复失败");
  }
};

// 处理评价
const handleRate = (row) => {
  rateForm.id = row.id;
  rateForm.complaintContent = row.complaintContent;
  rateForm.replyContent = row.replyContent;
  rateForm.satisfactionLevel = 0;
  rateDialogVisible.value = true;
};

// 提交评价
const submitRating = async () => {
  if (rateForm.satisfactionLevel <= 0) {
    ElMessage.warning("请先进行评分");
    return;
  }

  try {
    const response = await submitSatisfactionRating({
      id: rateForm.id,
      rating: rateForm.satisfactionLevel,
    });

    if (response.success) {
      ElMessage.success("评价提交成功");
      rateDialogVisible.value = false;
      fetchComplaintList(); // 刷新列表
    } else {
      ElMessage.error(response.message || "评价提交失败");
    }
  } catch (error) {
    console.error("提交评价失败:", error);
    ElMessage.error("提交评价失败");
  }
};

// 导出
const handleExport = async () => {
  await getComplaintReplyListExcel();
  ElMessage.success("导出成功");
};

// 根据评分获取提示文本
const getRatingTips = () => {
  const score = rateForm.satisfactionLevel;
  if (score <= 0) {
    return "请点击星星评分";
  } else if (score <= 2) {
    return "感谢您的反馈，我们会继续努力改进服务质量";
  } else if (score <= 3) {
    return "感谢您的评价，我们将不断提升服务水平";
  } else {
    return "感谢您的认可，我们将继续为您提供优质服务";
  }
};
</script>

<style scoped>
.complaint-list-container {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: calc(100vh - 84px);
}

/* 搜索过滤区样式 */
.search-card {
  margin-bottom: 16px;
  border-radius: 4px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.05);
}

/* 表格工具栏 */
.table-toolbar {
  display: flex;
  align-items: center;
  margin-bottom: 16px;
}

/* 表格区域 */
.table-card {
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.05);
}

:deep(.el-table__header) {
  background-color: #f5f7fa;
}

:deep(.el-table__header-wrapper th) {
  background-color: #f5f7fa;
  color: #606266;
  font-weight: 600;
  height: 50px;
}

:deep(.el-table__row td) {
  padding: 10px 0;
}

/* 分页容器 */
.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

/* 弹窗样式 */
:deep(.el-dialog) {
  border-radius: 8px;
}

:deep(.el-dialog__header) {
  border-bottom: 1px solid #f0f0f0;
  padding: 15px 20px;
}

:deep(.el-dialog__body) {
  padding: 20px;
}

:deep(.el-dialog__footer) {
  border-top: 1px solid #f0f0f0;
  padding: 15px 20px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
}

/* 评分样式 */
:deep(.el-rate) {
  display: inline-flex;
  line-height: 1;
}

:deep(.el-rate__text) {
  margin-left: 10px;
  font-size: 14px;
}

:deep(.el-rate__icon) {
  font-size: 24px;
  margin-right: 6px;
}
</style>
